package com.funtl.spring.cloud.alibaba.unit.config;

import com.funtl.spring.cloud.alibaba.unit.pojo.SysUser;
import com.funtl.spring.cloud.alibaba.unit.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @ClassName UserAuthencation
 * @Description TODO
 * @Author Mr.Starry
 * @Date 2020/1/4 14:11
 * @Version 1.0
 */
@Component
public class UserAuthencation implements UserDetailsService {

    private static Logger logger = LoggerFactory.getLogger(UserAuthencation.class);

    @Resource
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("访问-用户名："+ username);
        SysUser sysUser = sysUserService.getSysUserByUsername(username);
        //如果没有找到账号会抛出InternalAuthenticationServiceException ，抛出的时机是在 return new User之后
        if(null == sysUser) {
            throw new UsernameNotFoundException("用户不存在");
            //throw new InternalAuthenticationServiceException("用户不存在");
        }
        //String passwordEncode = "$2a$10$aio1nF/uRmomk6pWRlRsruJ4xdxJ8xMocvuC/euem9zGjzgij35Le";
        return new User(username, sysUser.getPassword(), Arrays.asList(new SimpleGrantedAuthority("admin")));
    }

    public static void main(String[] args) {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        System.out.println(passwordEncoder.encode("1"));
        //$2a$10$aio1nF/uRmomk6pWRlRsruJ4xdxJ8xMocvuC/euem9zGjzgij35Le
        //每一次生成的结果都不一样
    }
}
